Page({
  data: {
    tabs: ['全部', '待开票', '已开票'],
    currentTab: 0,
    invoices: [],
    statusBarHeight: 0,
    navbarHeight: 0
  },

  onLoad() {
    // 获取系统信息，用于适配状态栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 0
    // 导航栏总高度 = 状态栏高度 + 88rpx (导航栏内容高度，约44px)
    const navbarHeight = statusBarHeight + 44
    this.setData({
      statusBarHeight: statusBarHeight,
      navbarHeight: navbarHeight
    })
    this.loadInvoices()
  },

  onShow() {
    this.loadInvoices()
  },

  loadInvoices() {
    const invoices = wx.getStorageSync('invoices') || this.getMockInvoices()
    const filteredInvoices = this.filterInvoices(invoices, this.data.currentTab)
    
    this.setData({
      invoices: filteredInvoices.map(item => ({
        ...item,
        formattedAmount: item.amount.toFixed(2),
        formattedTime: this.formatTime(item.createTime),
        formattedIssueTime: item.issueTime ? this.formatTime(item.issueTime) : ''
      }))
    })
  },

  getMockInvoices() {
    return [
      {
        id: 1,
        invoiceNo: 'INV20240619001',
        orderNo: 'ORD20240619001',
        type: 'personal', // personal-个人, company-企业
        title: '个人',
        amount: 999,
        status: 'pending', // pending-待开票, issued-已开票
        createTime: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(),
        issueTime: null,
        taxNumber: ''
      },
      {
        id: 2,
        invoiceNo: 'INV20240620002',
        orderNo: 'ORD20240620002',
        type: 'company',
        title: '北京科技有限公司',
        amount: 1200,
        status: 'issued',
        createTime: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(),
        issueTime: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
        taxNumber: '91110000MA01234567'
      },
      {
        id: 3,
        invoiceNo: 'INV20240621003',
        orderNo: 'ORD20240621003',
        type: 'personal',
        title: '个人',
        amount: 367,
        status: 'pending',
        createTime: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
        issueTime: null,
        taxNumber: ''
      }
    ]
  },

  filterInvoices(invoices, tabIndex) {
    if (tabIndex === 0) {
      return invoices
    } else if (tabIndex === 1) {
      return invoices.filter(item => item.status === 'pending')
    } else {
      return invoices.filter(item => item.status === 'issued')
    }
  },

  formatTime(timeStr) {
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  switchTab(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentTab: index
    })
    this.loadInvoices()
  },

  applyInvoice() {
    wx.navigateTo({
      url: '/pages/invoice-apply/invoice-apply'
    })
  },

  viewInvoiceDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/invoice-detail/invoice-detail?id=${id}`
    })
  },

  downloadInvoice(e) {
    // 阻止事件冒泡，避免触发列表项的点击事件
    e.stopPropagation()
    
    const id = e.currentTarget.dataset.id
    const invoice = this.data.invoices.find(item => item.id === id)
    
    if (!invoice) {
      wx.showToast({
        title: '发票信息不存在',
        icon: 'none'
      })
      return
    }
    
    if (invoice.status !== 'issued') {
      wx.showToast({
        title: '发票尚未开具',
        icon: 'none'
      })
      return
    }
    
    // 显示加载提示
    wx.showLoading({
      title: '下载中...',
      mask: true
    })
    
    // 生成发票下载URL（实际项目中应该从服务器获取）
    const invoiceUrl = this.getInvoiceDownloadUrl(invoice)
    
    // 下载发票文件
    wx.downloadFile({
      url: invoiceUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存文件到本地
          wx.saveFile({
            tempFilePath: res.tempFilePath,
            success: (saveRes) => {
              wx.hideLoading()
              
              // 打开文档预览
              wx.openDocument({
                filePath: saveRes.savedFilePath,
                fileType: 'pdf',
                success: () => {
                  wx.showToast({
                    title: '下载成功',
                    icon: 'success',
                    duration: 2000
                  })
                },
                fail: (err) => {
                  console.error('打开文档失败:', err)
                  wx.showToast({
                    title: '打开失败，请检查文件',
                    icon: 'none'
                  })
                }
              })
            },
            fail: (err) => {
              wx.hideLoading()
              console.error('保存文件失败:', err)
              
              // 如果保存失败，尝试直接打开临时文件
              wx.openDocument({
                filePath: res.tempFilePath,
                fileType: 'pdf',
                success: () => {
                  wx.showToast({
                    title: '已打开发票',
                    icon: 'success'
                  })
                },
                fail: () => {
                  wx.showToast({
                    title: '下载失败，请重试',
                    icon: 'none'
                  })
                }
              })
            }
          })
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '下载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        wx.hideLoading()
        console.error('下载文件失败:', err)
        
        // 如果是模拟数据，显示提示
        if (err.errMsg && err.errMsg.includes('fail')) {
          // 模拟下载成功（用于演示）
          this.simulateDownload(invoice)
        } else {
          wx.showToast({
            title: '下载失败，请检查网络',
            icon: 'none'
          })
        }
      }
    })
  },

  // 获取发票下载URL（实际项目中应该从服务器获取）
  getInvoiceDownloadUrl(invoice) {
    // 这里应该调用后端API获取真实的发票下载地址
    // 暂时使用模拟URL
    return `https://example.com/invoices/${invoice.invoiceNo}.pdf`
  },

  // 模拟下载（用于演示，当真实URL不可用时）
  simulateDownload(invoice) {
    wx.showModal({
      title: '提示',
      content: `发票 ${invoice.invoiceNo} 下载功能演示\n\n在实际项目中，此功能将下载真实的发票PDF文件。`,
      showCancel: false,
      confirmText: '知道了',
      success: () => {
        // 模拟保存发票信息到本地
        const savedInvoices = wx.getStorageSync('downloadedInvoices') || []
        if (!savedInvoices.find(item => item.id === invoice.id)) {
          savedInvoices.push({
            id: invoice.id,
            invoiceNo: invoice.invoiceNo,
            downloadTime: new Date().toISOString()
          })
          wx.setStorageSync('downloadedInvoices', savedInvoices)
        }
        
        wx.showToast({
          title: '下载成功（演示）',
          icon: 'success'
        })
      }
    })
  },

  goBack() {
    wx.navigateBack()
  }
})

